<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title><%= baseName %> - Swagger UI</title>
    <base href="/swagger-ui/" />
    <link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
    <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
  </head>

  <body>
    <div id="swagger-ui"></div>

    <script src="./swagger-ui-bundle.js"></script>
    <script src="./swagger-ui-standalone-preset.js"></script>
    <script src="./axios.min.js"></script>

    <script type="text/javascript">
      const AlwaysEnableTryItOutPlugin = function () {
        return {
          components: {
            TryItOutButton: () => null,
          },
        };
      };

<%_ if (authenticationUsesCsrf) { _%>
        function getCSRF() {
          const name = 'XSRF-TOKEN=';
          const ca = document.cookie.split(';');
          for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1);
            if (c.includes(name)) return c.substring(name.length, c.length);
          }
          return '';
        }
<%_ } else { _%>
        const getBearerToken = () => {
          let authToken = localStorage.getItem('<%= jhiPrefixDashed %>-authenticationToken') || sessionStorage.getItem('<%= jhiPrefixDashed %>-authenticationToken');
          if (authToken) {
<%_ if (clientFrameworkAngular || clientFrameworkReact) { _%>
            authToken = JSON.parse(authToken);
<%_ } _%>
            return `Bearer ${authToken}`;
          }
          return null;
        };
<%_ } _%>

      function createAxiosConfig(serverBaseUri) {
        return {
          timeout: 5000,
          baseURL: serverBaseUri,
<%_ if (!authenticationUsesCsrf) { _%>
          headers: { Authorization: getBearerToken() },
<%_ } _%>
        };
      }

      async function fetchUrls(serverBaseUri, axiosConfig, baseUrl) {
        let urls;
<%_ if ((!applicationTypeMonolith && serviceDiscoveryAny) || (gatewayRoutes ?? []).length > 0) { _%>

        try {
  <%_ if ((gatewayRoutes ?? []).length > 0) { _%>
          const services = [<%- [{ route: lowercaseBaseName }, ...(gatewayRoutes ?? [])].map(({ route }) => `'${route}'`) %>];
  <%_ } else { _%>
          const response = await axios.get('/management/health/discoveryComposite', axiosConfig);
          const services = response.data?.components?.discoveryClient?.details?.services<% if (serviceDiscoveryConsul) { %>.filter(service => service !== 'consul')<% } %>;
  <%_ } _%>
          console.log(`Services`, services);

          if (services && services.length > 0) {
            urls = (
              await Promise.allSettled(
                services.map(async service => {
                  return axios
                    .get(`/services/${service}/management/jhiopenapigroups`, axiosConfig)
                    .then(response => {
                      if (Array.isArray(response.data)) {
                        return response.data.map(({ group, description }) => ({
                          name: description,
                          url: `/services/${service}/${baseUrl}/${group}`,
                        }));
                      }
                      return undefined;
                    })
                    .catch(() => {
                      return axios
                        .get(`/services/${service}/${baseUrl}`, axiosConfig)
                        .then(() => [{ url: `/services/${service}/${baseUrl}`, name: `${service} (default)` }]);
                    });
                }),
              )
            )
              .filter(settled => settled.status === 'fulfilled')
              .map(settled => settled.value)
              .filter(Array.isArray)
              .flat();
          }

        } catch (error) {
          console.log(error);
        }
<%_ } _%>

        if (!urls || urls.length === 0) {
          try {
            const response = await axios.get('/management/jhiopenapigroups', axiosConfig);
            if (Array.isArray(response.data)) {
              urls = response.data.map(({ group, description }) => ({ name: description, url: `${serverBaseUri}${baseUrl}/${group}` }));
            }
          } catch (error) {
            console.error('Failed to fetch default API docs', error);
          }
        }
        console.log(`Swagger urls`, urls);

        return urls?.length ? urls : [{ name: 'default', url: `${serverBaseUri}${baseUrl}` }];
      }

      function sortUrls(urls) {
        if (!urls) return urls;

        urls.sort((a, b) => compareUrls(a.name.toLowerCase(), b.name.toLowerCase()));

        return urls;
      }

      function compareUrls(nameA, nameB) {
        if (nameA.includes('(default)')) return -1;
        if (nameB.includes('(default)')) return 1;
        if (nameA.includes('(management)')) return -1;
        if (nameB.includes('(management)')) return 1;
        return nameA.localeCompare(nameB);
      }

      function initializeSwaggerUI(urls, baseUrl) {
        // Build a system
        const ui = SwaggerUIBundle({
          urls: urls,
          url: baseUrl,
          dom_id: '#swagger-ui',
          deepLinking: true,
          filter: true,
          layout: 'StandaloneLayout',
          withCredentials: true,
          presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
          plugins: [SwaggerUIBundle.plugins.DownloadUrl, AlwaysEnableTryItOutPlugin],
          tryItOutEnabled: true,
          requestInterceptor: function (req) {
<%_ if (authenticationUsesCsrf) { _%>
            req.headers['X-XSRF-TOKEN'] = getCSRF();
<%_ } else { _%>
            req.headers['Authorization'] = getBearerToken();
<%_ } _%>
            // Remove the sample Swagger UI request body if present
            if (req.method === 'GET' && req.body === '{"additionalProp1":"string","additionalProp2":"string","additionalProp3":"string"}') {
              req.body = undefined;
            }
            return req;
          },
        });

        globalThis.ui = ui;
      }

      globalThis.onload = async function () {
        const baseUrl = 'v3/api-docs';
        const serverBaseUri = document.baseURI.replace('swagger-ui/', '');
        const axiosConfig = createAxiosConfig(serverBaseUri);
        const urls = await fetchUrls(serverBaseUri, axiosConfig, baseUrl);
        const sortedUrls = sortUrls(urls);

        initializeSwaggerUI(sortedUrls, baseUrl);
      };
    </script>
  </body>
</html>
